<template>
  <t-form
    ref="form"
    class="base-form"
    :data="formData"
    :rules="FORM_RULES"
    label-align="left"
    :label-width="80"
    @submit="onSubmit"
  >
    <div class="form-basic-container">
      <div class="form-basic-item">
        <!-- <div class="form-basic-container-title">表单信息</div> -->
        <!-- 表单内容 -->
        <t-form-item label="商户号" name="mchId">
          <t-input v-model="formData.mchId" :style="{ width: '322px' }" placeholder="请输入内容" />
        </t-form-item>
        <t-form-item label="AppId" name="appId">
          <t-input v-model="formData.appId" :style="{ width: '322px' }" placeholder="请输入内容" />
        </t-form-item>
        <t-form-item label="订单号" name="orderNo">
          <t-input v-model="formData.orderNo" :style="{ width: '230px' }" placeholder="请输入内容" /><t-button
            variant="dashed"
            @click="fetchData"
            >随机生成</t-button
          >
        </t-form-item>
        <t-form-item label="支付额度" name="payAmount">
          <t-input-adornment append="元">
            <t-input-number
              v-model="formData.payAmount"
              theme="column"
              :min="0.1"
              :style="{ width: '140px' }"
              placeholder="请输入支付额度"
              @change="fetchData"
            />
          </t-input-adornment>
        </t-form-item>
        <t-form-item label="回调地址" name="returnUrl">
          <t-input v-model="formData.returnUrl" :style="{ width: '322px' }" placeholder="回调地址" />
        </t-form-item>

        <t-form-item label="">
          <t-space>
            <t-button
              v-if="cashierUrl !== ''"
              theme="danger"
              class="form-submit-confirm"
              :disabled="sending"
              @click="jump"
            >
              去收银台完成支付
            </t-button>
            <t-button theme="default" class="form-submit-confirm" type="submit" :disabled="sending">
              支付测试请求
            </t-button>
          </t-space>
        </t-form-item>
      </div>
    </div>
  </t-form>

  <div ref="alipayWap" v-html="alipayHtml"></div>

  <response :data="resData"></response>
  <t-dialog v-model:visible="visibleDialog" :footer="null" width="270" header="手机扫码">
    <qrcode-vue :value="qrcodeValue" :size="192" level="H" />
  </t-dialog>
</template>

<script lang="ts">
export default {
  name: 'AlipayRequestForm',
};
</script>

<script setup lang="ts">
import { ref, reactive, defineProps, onMounted, nextTick } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import QrcodeVue from 'qrcode.vue';
import Response from './Response.vue';
import { PREPAY_PARAMS } from '../constants';
import { AlipayPrepayOrder, AlipayPagePay, AlipayWapPay } from '@/api/test';

const props = defineProps({
  cashierUrl: {
    type: String,
  },
  scene: {
    type: String,
  },
});
const formData = ref({ ...PREPAY_PARAMS });
const FORM_RULES = {
  mchId: [{ required: true, message: '请输入必要信息', type: 'error' }],
  orderNo: [{ required: true, message: '请输入必要信息', type: 'error' }],
  appId: [{ required: true, message: '请输入必要信息', type: 'error' }],
  openId: [{ required: true, message: '请输入必要信息', type: 'error' }],
  payAmount: [{ required: true, message: '请输入必要信息', type: 'error' }],
};
const fetchData = () => {
  formData.value.returnUrl = window.location.href;
  // 自动生成订单号
  AlipayPrepayOrder(formData.value.payAmount).then((ret) => {
    formData.value.mchId = ret.mchId;
    formData.value.orderNo = ret.orderNo;
    formData.value.appId = ret.appId;
    formData.value.notifyUrl = ret.notifyUrl;
  });
};
const resData = reactive({
  request: {
    data: '',
    url: '',
  },
  response: {
    data: '',
  },
});

const sending = ref(false);
const alipayHtml = ref('');
const alipayWap = ref();
const prepay = () => {
  //  resData.request.data = JSON.stringify(formData.value);
  sending.value = true;
  // 发起支付
  if (props.scene === 'alipay.trade.page.pay') {
    resData.request.url = 'api/alipay/pagepay';
    pagePay();
  }
  if (props.scene === 'alipay.trade.wap.pay') {
    resData.request.url = 'api/alipay/wappay';
    wapPay();
  }
};

const pagePay = () => {
  AlipayPagePay({
    orderNo: formData.value.orderNo,
    orderName: '技术服务费',
    payAmount: formData.value.payAmount,
    returnUrl: formData.value.returnUrl,
    attach: '',
  })
    .then((ret) => {
      console.log('ret', JSON.stringify(ret));
      resData.response.data = JSON.stringify(ret);
      // alipayHtml.value = ret.body;
      // nextTick(() => {
      //   if (props.scene === 'alipay.trade.page.pay') {
      //     alipayWap.value.children[0].submit();
      //   }
      // });
    })
    .catch((e) => {
      resData.response.data = e.message;
      MessagePlugin.error(e.message);
    })
    .finally(() => {
      sending.value = false;
    });
};
const wapPay = () => {
  AlipayWapPay({
    orderNo: formData.value.orderNo,
    orderName: '技术服务费',
    payAmount: formData.value.payAmount,
    returnUrl: formData.value.returnUrl,
    attach: '',
  })
    .then((ret) => {
      console.log('ret', JSON.stringify(ret));
      resData.response.data = JSON.stringify(ret);
    })
    .catch((e) => {
      resData.response.data = e.message;
      MessagePlugin.error(e.message);
    })
    .finally(() => {
      sending.value = false;
    });
};
const onSubmit = ({ validateResult }) => {
  if (validateResult === true) {
    prepay();
  }
};
onMounted(() => {
  fetchData();
});

const qrcodeValue = ref('');
const visibleDialog = ref(false);

const jump = () => {
  // 生成二维码
  const url = `${props.cashierUrl}#/order/base?appid=${formData.value.appId}&orderNo=${formData.value.orderNo}&orderName=技术服务费&payAmount=${formData.value.payAmount}`;
  qrcodeValue.value = url;
  console.log(`url=${url}`);
  visibleDialog.value = true;
};
</script>

<style lang="less" scoped></style>
